//
//  GUAServerRequest.m
//  GUAFrameCreate
//
//  Created by Guava on 16/1/27.
//  Copyright © 2016年 Guava. All rights reserved.
//

#import "GUAServerRequest.h"
#import <AFNetworking.h>
#import <AFHTTPSessionManager.h>
#import <MBProgressHUD.h>
#import "AppDelegate.h"

#import "BasicResult.h"
#import "GUATool.h"

@implementation GUAServerRequest

+ (void)GETWithURL:(nonnull NSString *)URL
        parameters:(nullable id)parameters
           success:(nullable void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))successResponse
           failure:(nullable void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failureResponse
            inView:(nullable UIView *)view
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    if(view == nil) {
        view = [UIApplication sharedApplication].delegate.window;
    }
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    hud.removeFromSuperViewOnHide = YES;
    NSLog(@"request URL ---------- %@",URL);
    [manager
     GET:URL
     parameters:parameters
     progress:nil
     success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
         NSLog(@"responseObject: %@",responseObject);
         /*--- 适应项目 ---*/
         BasicResult *result = [[BasicResult alloc] initWithDictionary:responseObject];
         if(result.success) successResponse(task,responseObject);
         else [GUATool showDialog:result.msg message:nil waitingTime:1.5];
         [hud hide:YES];
     }
     failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         NSLog(@"---------- request error ----------");
         NSLog(@"get request error: %@",error);
         failureResponse(task,error);
         [hud hide:YES];
     }];
}


/**
 如果遇到content-type 是 application/text的形式
 应该设置manager.requestSerializer = [AFJSONRequestSerializer serializer];
 */
+ (void)POSTWithURL:(nonnull NSString *)URL
         paramaters:(nullable id)parameters
            success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success
            failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure
             inView:(nullable UIView *)view
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.requestSerializer.timeoutInterval = 30;
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/x-json",@"text/html",nil];
    
    if(view == nil) {
        view = [UIApplication sharedApplication].delegate.window;
    }
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    hud.removeFromSuperViewOnHide = YES;
    
    
    NSLog(@"request URL ---------- %@",URL);
    [manager
     POST:URL
     parameters:parameters
     progress:nil
     success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
         NSLog(@"responseObject: %@",responseObject);
         /*--- 适应快金所项目 ---*/
         BasicResult *result = [[BasicResult alloc] initWithDictionary:responseObject];
         NSLog(@"result: %@",result);
         if(result.success || [result.messageresult isEqualToString:@"0"] || [result.ReturnMessage isEqualToString:@"success"] || [result.returnMsg isEqualToString:@"success"] ){
             success(task,responseObject);
         }else if([result.MessageAccept isEqualToString:@"wrong"]){
             [GUATool showDialog:@"验证码错误" message:nil waitingTime:1.5];
         }else if(result._ERROR_MESSAGE_!=NULL){
             if ([result._ERROR_MESSAGE_ containsString:@"禁用"]) {
                 [GUATool showDialog:@"账户被锁定" message:nil waitingTime:1.5];
             }else if ([result._ERROR_MESSAGE_ containsString:@"密码不正确"]){
                 [GUATool showDialog:@"密码错误" message:nil waitingTime:1.5];
             }else if ([result._ERROR_MESSAGE_ containsString:@"没有找到用户"])
             {
                 [GUATool showDialog:@"该手机号码未注册，请先注册" message:nil waitingTime:2];
             }
         }else if (result._ERROR_MESSAGE_LIST_){
//            [GUATool showDialog:@"该手机号已注册" message:nil waitingTime:1.5];
             if ([result._ERROR_MESSAGE_LIST_.firstObject containsString:@"已存在"]) {
                 [GUATool showDialog:@"手机号已注册" message:nil waitingTime:1.5];
             }
         }else if (result.describe != NULL){
             [GUATool showDialog:result.describe message:nil waitingTime:1.5];
         }else if (result.returnMsg != NULL){
             if ([result.returnMsg isEqualToString:@"error"]){
                 [GUATool showDialog:@"更换失败" message:nil waitingTime:1.5];
             }else if ([result.returnMsg isEqualToString:@"exist"]){
                 [GUATool showDialog:@"新手机号码存在" message:nil waitingTime:1.5];
             }else if ([result.returnMsg isEqualToString:@"wrong"]){
                 [GUATool showDialog:@"操作失败" message:nil waitingTime:1.5];
             }else if ([result.returnMsg isEqualToString:@"nofind"]){
                 [GUATool showDialog:@"找不到用户" message:nil waitingTime:1.5];
             }else if ([result.returnMsg isEqualToString:@"wrongoldpassword"]){
                 [GUATool showDialog:@"旧密码错误" message:nil waitingTime:1.5];
             }
         }else [GUATool showDialog:result.msg message:nil waitingTime:1.5];
    
         [hud hide:YES];
     }
     failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         NSLog(@"post request error: %@",error);
         failure(task,error);
         [hud hide:YES];
     }];
}

+ (void)silencedGETWithURL:(NSString *)URL parameters:(id)parameters success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))successResponse failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failureResponse {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
   
    NSLog(@"request URL ---------- %@",URL);
    [manager
     GET:URL
     parameters:parameters
     progress:nil
     success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
         NSLog(@"responseObject: %@",responseObject);
         /*--- 适应项目 ---*/
         BasicResult *result = [[BasicResult alloc] initWithDictionary:responseObject];
         if(result.success) successResponse(task,responseObject);
         else [GUATool showDialog:result.msg message:nil waitingTime:1.5];
     
     }
     failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         NSLog(@"---------- request error ----------");
         NSLog(@"get request error: %@",error);
//         failureResponse(task,error);
     }];

}

+ (void)silencedPOSTWithURL:(NSString *)URL paramaters:(id)parameters success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 30;
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    
    NSLog(@"request URL ---------- %@",URL);
    [manager
     POST:URL
     parameters:parameters
     progress:nil
     success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
         NSLog(@"responseObject: %@",responseObject);
         /*--- 适应项目 ---*/
         BasicResult *result = [[BasicResult alloc] initWithDictionary:responseObject];
         if(result.success) success(task,responseObject);
         else [GUATool showDialog:result.msg message:nil waitingTime:1.5];
     
     }
     failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         NSLog(@"post request error: %@",error);
         failure(task,error);
     }];
}

+ (void)postImageWithUrl:(NSString *)url
         imageDictionary:(NSDictionary<NSString *,NSData *> *)imageDictinary
              parameters:(id)parameters
                 success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.requestSerializer.timeoutInterval = 30;
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"text/plain",@"application/json",@"application/x-json", nil];

    UIView *view = [UIApplication sharedApplication].delegate.window;
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    hud.removeFromSuperViewOnHide = YES;
    
    NSLog(@"request URL ---------- %@",url);

    [manager POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSArray *imageNameArray = [imageDictinary allKeys];
        for(NSString *key in imageNameArray) {
            [formData appendPartWithFileData:imageDictinary[key] name:key fileName:[NSString stringWithFormat:@"%@.jpg",key] mimeType:@"image/jpeg"];
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"responseObject: %@",responseObject);

        [hud hide:YES];
        /*--- 适应项目 ---*/
        
        BasicResult *result = [[BasicResult alloc] initWithDictionary:dic];
        NSLog(@"result: %@",result);

        if(result.success) success(task,dic);
        else [GUATool showDialog:result.msg message:nil waitingTime:1.5];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [hud hide:YES];
        NSLog(@"post request error: %@",error);

        failure(task, error);
    }];
}

@end
